
package com.putao.album.child;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.R;
import com.putao.album.album.ActivityAlbumPhotoSelect;
import com.putao.album.application.GlobalApplication;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.bean.Child;
import com.putao.album.child.crop.ActivityCropImage;
import com.putao.album.dialog.DialogBuilderFactory;
import com.putao.album.dialog.SelectDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.main.AlbumHomeActivity;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.BitmapHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15-4-27.
 */
public class ActivityChildAdd extends BaseActivity {
    private TextView title_tv, birthday, relation;
    private LinearLayout sex_boy, sex_girl, sex_noBorn, ll_code;
    private Button back_btn, right_btn;
    private EditText nick_name;
    private String uploadToken;
    private String photo_path;
    private ImageView child_icon;
    private Child child;
    private Button done;
    private ProgressDialog dialog;
    private boolean isRegister;
    private boolean isSide = false;


    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.back_btn:
                if (isRegister) {
                    ActivityHelper.startActivity(mActivity, AlbumHomeActivity.class);
                }
                mActivity.finish();
                break;
            case R.id.right_btn:
                ActivityHelper.startActivity(mActivity, ActivityChildConnect.class);
                break;
            case R.id.child_icon:
                //                bundle.putBoolean("multiSelectState", false);
                //                ActivityHelper.startActivity(mActivity, ActivityAlbumPhotoSelect.class, bundle);
                showSeLectDialog();
                break;
            case R.id.birthday:
                selectBirthday();
                break;
            case R.id.relation:
                bundle.putString("relation", relation.getText().toString());
                ActivityHelper.startActivity(mActivity, ActivityChildSelectRelation.class, bundle);
                break;
            case R.id.sex_boy:
            case R.id.sex_girl:
            case R.id.sex_noBorn:
                childSexSetSelect(v.getId());
                break;
            case R.id.done:
                dialog = new ProgressDialog(mContext);
                dialog.setMessage(getString(R.string.loading));
                dialog.setCancelable(false);
                dialog.show();
                getUploadToken();
                break;
            case R.id.empty_invite_baby_btn:
                ActivityHelper.startActivity(mActivity, ActivityChildConnect.class);
                break;
            default:
                break;
        }
    }

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_child_add;
    }

    @Override
    public void doInitSubViews(View view) {
        back_btn = (Button) findViewById(R.id.back_btn);
        back_btn.setBackgroundResource(R.drawable.all_button_close);
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(R.string.child_add_title);
        right_btn = (Button) findViewById(R.id.right_btn);
        right_btn.setVisibility(View.GONE);
        queryViewById(R.id.empty_invite_baby_btn, true);
//        right_btn.setText("我有邀请码");
//        right_btn.setTextColor(getResources().getColor(R.color.white));
//        right_btn.setBackgroundResource(R.drawable.background_btn_blue);
//        right_btn.setTextSize(14);
        child_icon = (ImageView) findViewById(R.id.child_icon);
        nick_name = (EditText) findViewById(R.id.nick_name);
        birthday = (TextView) findViewById(R.id.birthday);
        relation = (TextView) findViewById(R.id.relation);
        done = (Button) findViewById(R.id.done);
        sex_boy = (LinearLayout) findViewById(R.id.sex_boy);
        sex_girl = (LinearLayout) findViewById(R.id.sex_girl);
        sex_noBorn = (LinearLayout) findViewById(R.id.sex_noBorn);
        ll_code = queryViewById(R.id.ll_code);
        sex_boy.setSelected(true);
        String curTime = new SimpleDateFormat(getString(R.string.time_format_year_month_day)).format(new Date(System.currentTimeMillis()));
        birthday.setText(curTime);
        addOnClickListener(back_btn, right_btn, child_icon, birthday, relation, sex_boy, sex_girl, sex_noBorn, done);
        EventBus.getDefault().register(this);
    }

    @Override
    public void doInitData() {
        try {
            if (getIntent() != null) {
                Bundle bundle = getIntent().getExtras();
                if (bundle != null) {
                    isRegister = bundle.getBoolean("isRegister", false);
                    isSide = bundle.getBoolean("isSide", false);
                    if (isSide) {
                        ll_code.setVisibility(View.GONE);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        child = new Child();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        MobclickAgent.onEvent(mContext, UmengTouchEvent.CANCEL_CREATEBABY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_FINISH_PHOTO_SELECT:
                photo_path = event.bundle.getString("photo_path");
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .considerExifParams(true)
                        .build();
                ImageLoader.getInstance().displayImage("file://" + photo_path, child_icon, options);
                break;
            case PuTaoConstants.EVENTBUS_FINISH_RELATION_SELECT:
                String relation = event.bundle.getString("relation");
                this.relation.setText(relation);
                break;
            case PuTaoConstants.EVENTBUS_RELATE_BABY_SUCCESS:
                finish();
                break;
        }
    }

    private void selectBirthday() {
        int year, month, day;
        String value = birthday.getText().toString();
        DateFormat format = new SimpleDateFormat(getString(R.string.time_format_year_month_day));
        Date date = null;
        if (!StringHelper.isEmpty(value)) {
            try {
                date = format.parse(value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Calendar c = Calendar.getInstance();
        if (date != null) {
            c = new GregorianCalendar();
            c.setTime(date);
        }
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        Dialog dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                Date date = new Date(new GregorianCalendar(year, month, dayOfMonth).getTimeInMillis());
                String time = new SimpleDateFormat(getString(R.string.time_format_year_month_day)).format(date);
                birthday.setText(time);
            }
        }, year, // 传入年份
                month, // 传入月份
                day// 传入天数
        );
        dialog.show();
    }

    /**
     * 活取上传图像的Token
     */
    private void getUploadToken() {
        if (StringHelper.isEmpty(nick_name.getText().toString())) {
            showToast(getString(R.string.please_input_nickname));
            dialog.dismiss();
            return;
        }
        if (StringHelper.isEmpty(relation.getText().toString())) {
            showToast(getString(R.string.please_select_relation));
            dialog.dismiss();
            return;
        }
        //http://api.camera.putao.io/policy/policy/getUploadToken?type=addAvatar
        //type:addAvatar.添加头像  editAvatar.编辑头像 uploadPhotos.上传宝宝照片
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("type", "addAvatar");
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_TOKEN, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)),
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                String uploadToken = json.getString("uploadToken");
                                setUploadTokeId(uploadToken);
                                addChild();
                            } else {
                                dialog.dismiss();
                            }
                        } catch (JSONException e) {
                            dialog.dismiss();
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                        dialog.dismiss();
                        showToast(getString(R.string.child_add_fail));
                    }
                });
    }

    /**
     *
     *
     */
    private void addChild() {
        RequestParams params = new RequestParams(new HttpRequestUtil().buildHttpRequestParams(new HashMap()));
        child.setName(nick_name.getText().toString());
        child.setBirthday(birthday.getText().toString());
        child.setRelation(relation.getText().toString());
        child.setSex(childSexGet());
        params.put("name", child.getName());
        params.put("birthday", child.getBirthday());
        params.put("sex", child.getSex());
        params.put("relationship", child.getRelation());
        params.put("uploadToken", getUploadTokeId());
        try {
            if (photo_path == null) {
                Bitmap bitmap;
                String childFile;
                String dir = GlobalApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                if (childSexGet().equals(Child.ChildSex.girl)) {
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.baby_icon_girl);
                    childFile = dir + "/baby_icon_girl.png";
                } else if (childSexGet().equals(Child.ChildSex.boy)) {
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.baby_icon_boy);
                    childFile = dir + "/baby_icon_boy.png";
                } else {
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.baby_icon_unborn);
                    childFile = dir + "/baby_icon_unborn.png";
                }


                if (!new File(childFile).exists()) {
                    FileOutputStream outStream = new FileOutputStream(childFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                }
                photo_path = childFile;
            }
            File file = new File(photo_path);
            params.put("file", file);
        } catch (Exception e) {
            e.printStackTrace();
            dialog.dismiss();
        }
        HttpRequestUtil.doFileUploadRequest(mContext, PuTaoConstants.API_UPLOAD_UPLOAD_UPLOAD, params, new HttpRequestUtil.FileUploadRequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                //                        {"status":"200","msg":"创建成功","data":{"baby_id":"40","avatar":"http:\/\/file.dev.putao.io\/6\/fd\/6fd7595cd981809a21a93a9de9b7bcc26efb08c0.jpg"}}
                try {
                    JSONObject json = new JSONObject(response);
                    String status = json.getString("status");
                    String message = json.getString("msg");
                    String data = json.getString("data");
                    //解析返结果data中的参数
                    json = new JSONObject(data);
                    String baby_id = json.getString("baby_id");
                    //上传成功的图像地址
                    String avatar = json.getString("avatar");
                    if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        child.setId(baby_id);
                        child.setAvatar(avatar);
                        showToast(getString(R.string.child_add_success));
                        //save child to db
                        CommonUtils.saveBabyId(child.getId());
                        Bundle bundle = new Bundle();
                        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_ADD_CHILD_SUCCESS, bundle));

                        bundle.putBoolean("isRegister", isRegister);
                        ActivityHelper.startActivity(mActivity, ActivityAlbumPhotoSelect.class, bundle);
                        MobclickAgent.onEvent(mContext, UmengTouchEvent.CREATE_BABY);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    dialog.dismiss();
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.i("response:" + response);
                dialog.dismiss();
            }

            @Override
            public void onprogress(int bytesWritten, int totalSize) {
            }
        });
    }

    /**
     * 上传图片的Token
     *
     * @param uploadToken
     */
    private void setUploadTokeId(String uploadToken) {
        this.uploadToken = uploadToken;
    }

    /**
     * 上传图片的Token
     *
     * @return String
     */
    private String getUploadTokeId() {
        return uploadToken;
    }

    private void childSexSetSelect(int viewId) {
        sex_boy.setSelected(false);
        sex_girl.setSelected(false);
        sex_noBorn.setSelected(false);
        LinearLayout view = (LinearLayout) findViewById(viewId);
        view.setSelected(true);
        if (photo_path == null) {
            if (Child.ChildSex.girl.equals(childSexGet())) {
                child_icon.setImageResource(R.drawable.baby_icon_girl);
            } else if (Child.ChildSex.boy.equals(childSexGet())) {
                child_icon.setImageResource(R.drawable.baby_icon_boy);
            } else {
                child_icon.setImageResource(R.drawable.baby_icon_unborn);
            }
        }
    }

    private String childSexGet() {
        if (sex_girl.isSelected()) {
            return Child.ChildSex.girl;
        } else if (sex_noBorn.isSelected()) {
            return Child.ChildSex.noBorn;
        } else {
            return Child.ChildSex.boy;
        }
    }

    void showSeLectDialog() {
        SelectDialogBuilder.DialogButtonOnClickListener mDialogListener = new SelectDialogBuilder.DialogButtonOnClickListener() {
            @Override
            public void positiveOnClick(Dialog dialog) {
                startCameraApp();
                dialog.dismiss();
            }

            @Override
            public void negativeOnClick(Dialog dialog) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("multiSelectState", false);
                ActivityHelper.startActivity(mActivity, ActivityAlbumPhotoSelect.class, bundle);
                dialog.dismiss();
            }
        };
        Dialog dialog = new DialogBuilderFactory<SelectDialogBuilder>(mContext, DialogBuilderFactory.DialogType.SELECT).Builder()
                .setDialogButtonOnClickListener(mDialogListener)
                .setNegativeButton("从相册选择照片").setPositiveButton("拍照").Create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private Uri mPhotoUri;
    private static final int REQUEST_CODE_PHOTO_SELECT = 2;

    private void startCameraApp() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            ContentValues contentValues = new ContentValues(2);
            contentValues.put(MediaStore.Images.Media.DATA, CommonUtils.getOutputMediaFile().getPath());
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
            startActivityForResult(intent, REQUEST_CODE_PHOTO_SELECT);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PHOTO_SELECT && resultCode == RESULT_OK) {
            Uri uri = null;
            if (data != null && data.getData() != null) {
                uri = data.getData();
            }
            if (uri == null) {
                if (mPhotoUri != null) {
                    uri = mPhotoUri;
                }
            }
            try {
                String[] projection = {MediaStore.MediaColumns._ID, MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(uri, projection, null, null, null);
                c.moveToFirst();
                String photoFileName = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                File file = new File(photoFileName);
                File destDir = CommonUtils.getOutputMediaDir();
                file.renameTo(destDir);
                photo_path = destDir.getPath() + File.separator + file.getName();
                final String[] SCAN_TYPES = {"image/jpeg"};
                MediaScannerConnection.scanFile(mContext, new String[]{photo_path}, SCAN_TYPES, null);

                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                        .cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
                        .considerExifParams(true)
                        .build();
                ImageLoader.getInstance().displayImage("file://" + photo_path, child_icon, options);

                Bundle bundle = new Bundle();
                bundle.putString("photo_path", photo_path);
                ActivityHelper.startActivity(mActivity, ActivityCropImage.class, bundle);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            getContentResolver().delete(mPhotoUri, null, null);
        }
    }
}
